package org.x.user.controller;

import com.aizuda.bpm.engine.FlowLongEngine;
import com.aizuda.bpm.engine.core.FlowCreator;
import jakarta.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;
import org.x.common.base.result.Result;
import org.x.common.base.util.UserContextHolder;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/flow")
public class FlowController {

    Logger logger = LoggerFactory.getLogger(FlowController.class);

    @Resource
    private FlowLongEngine flowLongEngine;

    // 部署流程
    @PostMapping("/deploy")
    public Result deploy(@RequestBody String jsonString) {

        try (InputStream inputStream = new ByteArrayInputStream(jsonString.getBytes())) {
            FlowCreator flowCreator = FlowCreator.of(UserContextHolder.getTenantId(),UserContextHolder.getUserId(),UserContextHolder.getUserName());
            Long processId = flowLongEngine.processService().deploy(inputStream, flowCreator, true);
            return Result.success(processId);
        } catch (Exception e) {
            logger.error("部署流程失败", e);
            throw new RuntimeException("部署流程失败", e);
        }
    }

    //启动流程
    @PostMapping("/start")
    public String start(@RequestParam Long processId, @RequestBody Map<String, Object> params) {
        FlowCreator flowCreator = FlowCreator.of(UserContextHolder.getTenantId(),UserContextHolder.getUserId(),UserContextHolder.getUserName());
        flowLongEngine.startInstanceById(processId, flowCreator, params).ifPresent(instance -> {
            // 其它流程操作
        });
        return "success";
    }
}
